<template>
  <div
    class="common-tooltip-text"
    :style="{ fontSize: `${fontSize}px` }"
    ref="container"
  >
    <!-- <span class="hidden-text" ref="hiddenText" v-show="false">
      {{ content }}
    </span> -->
    <!-- 如果isover超过了长度就用tip去提示，如果没有就直接展示 -->
    <!-- 如果页面发生变化，就重新渲染div -->
    <div class="show-text" v-if="!isOver">
      {{ content }}
    </div>
    <div class="show-tooltip-text" v-else>
      <el-tooltip
        class="item"
        :effect="effect"
        :content="content"
        :placement="placement"
      >
        <!-- 文本过长这个地方用省略号，用样式调整做出省略号 -->
        <div class="show-tooltip-text-content">
          {{ content }}
        </div>
      </el-tooltip>
    </div>
    <span
      class="full-text"
      v-if="showFullText"
      ref="fullText"
      :style="{ fontSize: `${fontSize}px` }"
    >
      {{ content }}</span
    >
  </div>
</template>

<script>
export default {
  name: "index",
  props: {
    content: {
      type: [String, Number],
      default: () => null,
    },
    placement: {
      type: String,
      default: "top",
    }, // 位置
    effect: {
      type: String,
      default: "dark",
    }, // 主题 dark || light
    fontSize: {
      type: Number,
      default: () => 14,
    },
  },
  data() {
    return {
      isOver: false,
      showFullText: false,
    };
  },
  watch: {
    content: {
      handler(newVal, oldVal) {
        if (newVal) {
          this.hanldeLength();
        }
      },
      immediate: true,
    },
  },
  mounted() {
    window.addEventListener("resize", this.hanldeLength);
  },
  beforeDestroy() {
    // 在组件销毁前，移除resize事件监听
    window.removeEventListener("resize", this.hanldeLength);
  },
  methods: {
    hanldeLength() {
      this.showFullText = true;
      this.$nextTick(() => {
        // console.log("fullText:", this.$refs.fullText.getBoundingClientRect());
        // console.log("container:", this.$refs.container.getBoundingClientRect());
        let fullText = this.$refs.fullText.getBoundingClientRect().width,
          container = this.$refs.container.getBoundingClientRect().width;
        this.isOver = fullText > container;
        this.showFullText = false;
      });
    },
  },
};
</script>

<style scoped lang="scss">
.common-tooltip-text {
  width: 100%;
  position: relative;

  .hidden-text {
    position: absolute;
  }

  .show-text,
  .show-tooltip-text-content {
    width: 100%;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .full-text {
    word-break: normal;
    white-space: nowrap;
  }
}
</style>
